<template>
  <el-form
    ref="searchRef"
    :model="searchForm"
    :inline="true"
  >
    <el-form-item>
      <el-input
        v-model="searchForm.name"
        placeholder="请输入关键字搜索"
      />
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        icon="Search"
        @click="onSearch(searchRef)"
      >
        搜索
      </el-button>
      <el-button
        type="primary"
        icon="Plus"
        @click="openAdd(formRef)"
      >
        添加
      </el-button>
    </el-form-item>
  </el-form>
  <el-main class="ea-table">
    <el-table
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        label="名称"
        width="150"
        align="center"
      />
      <!-- <el-table-column
        prop="type"
        label="类型"
        width="150"
        align="center"
      >
        <template #default="scope">
          {{ typeMap[scope.row.type] || '-' }}
        </template>
      </el-table-column> -->
      <el-table-column
        prop="factor"
        label="场景"
        width="120"
        align="center"
      >
        <template #default="scope">
          {{ factorMap[scope.row.status] || '-' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="content"
        label="回复内容"
        align="center"
      />
      <el-table-column
        prop="remark"
        label="提醒时间"
        width="150"
        align="center"
      >
        <template #default="scope">
          {{ `${scope.row.hour || 0}小时` }}
          {{ `${scope.row.minute || 0}分` }}
          {{ `${scope.row.second || 0}秒` }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="120"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.status ? '启用' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        fixed="right"
        width="150"
        align="center"
      >
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="openEdit(scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="onDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :background="true"
        layout="prev, pager, next, jumper"
        :total="pageTotal"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-main>

  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '修改' : '添加'"
    width="500"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="90"
    >
      <el-form-item
        label="名称:"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="发送内容:"
        prop="content"
      >
        <el-input
          v-model="formData.content"
          placeholder="请输入"
          type="textarea"
          :autosize="{ minRows: 4 }"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="选择场景:"
        prop="factor"
      >
        <el-radio-group v-model="formData.factor">
          <el-radio
            v-for="(item, index) in factorMap"
            :key="index"
            :value="index"
          >
            {{ item }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="formData.factor === 0"
        label="好友昵称:"
        prop="friendId"
      >
        <el-select
          v-model="formData.friendId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入好友昵称搜索"
          remote-show-suffix
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in friendsList"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="formData.factor === 1"
        label="选择群聊:"
        prop="roomId"
      >
        <el-select
          v-model="formData.roomId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in roomList"
            :key="item.id"
            :label="item.topic"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="时间单位:"
        prop="unit"
      >
        <el-radio-group v-model="formData.unit">
          <el-radio
            v-for="(item, index) in timeUnit"
            :key="index"
            :value="index"
          >
            {{ item }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="formData.unit >= 2"
        label="时:"
        prop="hour"
      >
        <el-input-number
          v-model="formData.hour"
          :min="0"
          :max="24"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item
        v-if="formData.unit >= 1"
        label="分:"
        prop="minute"
      >
        <el-input-number
          v-model="formData.minute"
          :min="0"
          :max="60"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item
        v-if="formData.unit >= 0"
        label="秒:"
        prop="second"
      >
        <el-input-number
          v-model="formData.second"
          :min="0"
          :max="60"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item
        label="状态:"
        prop="status"
      >
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">
            停用
          </el-radio>
          <el-radio :value="1">
            启用
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="editConfirm(formRef)"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="js">
import { userStore } from '@/stores'
import { nextTick, onMounted, reactive, ref, toRaw } from 'vue'
import { getTimeTaskList, addTimeTask, putTimeTask, deleteTimeTask } from '@/apis/timeTask'
import { getList } from '@/apis/myfriend'
import { getGroupList } from '@/apis/mygroup'
import { ElMessageBox } from 'element-plus'
import { viewLoading } from '@/stores/reactive'

// 场景
const factorMap = ['个人', '群聊', '通用群聊']
// 时间单位
const timeUnit = ['每分钟', '每小时', '每天']

const user = userStore()

const searchForm = reactive({
  name: ''
})
const searchRef = ref()
const searchVal = ref()
const tableData = ref([])
const roomList = ref([])
const friendsList = ref([])
const loading = ref(false)

const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

const currentRow = ref({})
const isEdit = ref(false)
const dialogVisible = ref(false)

const formRef = ref()
const formData = reactive({
  content: '',
  factor: null,
  name: '',
  robotId: user.robotId,
  roomId: null,
  friendId: null,
  status: 0,
  hour: null,
  minute: null,
  second: null,
  unit: null
})
const rules = reactive({
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  content: [{ required: true, message: '请输入', trigger: 'blur' }],
  factor: [{ required: true, message: '请选择', trigger: 'blur' }],
  roomId: [{ required: true, message: '请选择', trigger: 'blur' }],
  friendId: [{ required: true, message: '请选择', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择', trigger: 'blur' }],
  hour: [{ required: true, message: '请输入', trigger: 'blur' }],
  minute: [{ required: true, message: '请输入', trigger: 'blur' }],
  second: [{ required: true, message: '请输入', trigger: 'blur' }]
})

onMounted(() => {
  fetchList()
  fetchGroupList()
})

function fetchList () {
  if (user.robotId) {
    getTimeTaskList({ search$$robotId$$: user.robotId }).then(res => {
      tableData.value = res.data.list || []
      pageTotal.value = res.data.total
    })
  }
}

function fetchGroupList () {
  getGroupList({ id: user.robotId }).then(res => {
    roomList.value = res.data || []
  })
}

const onSearch = (formEl) => {
  if (!formEl) return
  const params = {
    search$$robotId$$: user.robotId
  }
  formEl.validate((valid) => {
    if (valid) {
      const val = searchForm.name
      if (val) {
        params.search$$name$$all = val
        searchVal.value = val
      }
      getTimeTaskList(params).then(res => {
        tableData.value = res.data.list || []
        pageTotal.value = res.data.total
      })
    }
  })
}

const handleCurrentChange = (val) => {
  const params = {
    search$$robotId$$: user.robotId,
    search$$name$$all: searchVal.value,
    page: val
  }
  getTimeTaskList(params).then(res => {
    tableData.value = res.data.list || []
    pageTotal.value = res.data.total
  })
}

const remoteMethod = (val) => {
  loading.value = true
  viewLoading.status = null
  getList({
    search$$robotId$$: user.robotId,
    search$$name$$all: val
  }, { viewLoading: true }).then(res => {
    if (res.success) {
      friendsList.value = res.data.list || []
      loading.value = false
    } else {
      friendsList.value = []
    }
  }).finally(() => {
    loading.value = false
    viewLoading.status = false
  })
}

const openAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  currentRow.value = {}
  formData.roomId = null
  formData.hour = null
  formData.minute = null
  nextTick(() => {
    formRef.value.resetFields()
  })
}

const openEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  currentRow.value = row

  formData.content = row.content
  formData.factor = row.factor
  formData.name = row.name
  formData.robotId = row.robotId
  formData.roomId = row.roomId
  formData.friendId = row.friendId
  formData.status = row.status
  formData.hour = row.hour
  formData.minute = row.minute
  formData.second = row.second
  formData.unit = row.unit
}
const onDelete = (row) => {
  ElMessageBox.confirm(
    '该操作数据不可逆，请谨慎操作!!!',
    '确定进行该操作吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '我再想想',
      type: 'warning'
    }
  ).then(() => {
    deleteTimeTask({ ids: [row._id] }).then(res => {
      res.success && fetchList()
    })
  })
}

const editConfirm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        if (!currentRow.value._id) return
        putTimeTask(
          currentRow.value._id,
          toRaw(formData)
        ).then(res => {
          if (res.success) {
            dialogVisible.value = false
            fetchList()
          }
        })
      } else {
        addTimeTask(toRaw(formData)).then(res => {
          if (res.success) {
            dialogVisible.value = false
            res.success && fetchList()
          }
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.page{
  background: #FFFFFF;
  padding: 10px 10px 10px 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
